/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.fee.util.Exportprofit;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.wms.util.ExportU;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.fee.entity.Profit;
import com.jeeplus.modules.fee.service.ProfitService;

/**
 * 利润分析Controller
 * @author 李超辉
 * @version 2018-05-22
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/profit")
public class ProfitController extends BaseController {

	@Autowired
	private ProfitService profitService;
	
	@ModelAttribute
	public Profit get(@RequestParam(required=false) String id) {
		Profit entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = profitService.get(id);
		}
		if (entity == null){
			entity = new Profit();
		}
		return entity;
	}
	
	/**
	 * 利润分析列表页面
	 */
	@RequiresPermissions("fee:profit:list")
	@RequestMapping(value = {"list", ""})
	public String list(Profit profit,HttpServletRequest request,Model model, HttpServletResponse response) {
		return "modules/fee/profitList";
	}

	/**
	 * 利润分析列表页面
	 */
	@RequiresPermissions("fee:profit:list")
	@RequestMapping(value = "list1")
	public String list1(Profit profit,HttpServletRequest request,Model model, HttpServletResponse response) {

		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			profit.setPro(pro);
		}
		Page<Profit> page = profitService.findPage(new Page<Profit>(request, response), profit);

		return "modules/fee/2/profitList";
	}
	
		/**
	 * 利润分析列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fee:profit:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Profit profit, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro= UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			profit.setPro(pro);
		}
		Page<Profit> page = profitService.findPage(new Page<Profit>(request, response), profit);
		return getBootstrapData(page);

	}

	/**
	 * 查看，增加，编辑利润分析表单页面
	 */
	@RequiresPermissions(value={"fee:profit:view","fee:profit:add","fee:profit:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Profit profit, Model model) {
		model.addAttribute("profit", profit);
		return "modules/fee/profitForm";
	}

	/**
	 * 保存利润分析
	 */
	@ResponseBody
	@RequiresPermissions(value={"fee:profit:add","fee:profit:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Profit profit, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, profit)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		profitService.save(profit);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存利润分析成功");
		return j;
	}
	
	/**
	 * 删除利润分析
	 */
	@ResponseBody
	@RequiresPermissions("fee:profit:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Profit profit, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		profitService.delete(profit);
		j.setMsg("删除利润分析成功");
		return j;
	}
	
	/**
	 * 批量删除利润分析
	 */
	@ResponseBody
	@RequiresPermissions("fee:profit:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			profitService.delete(profitService.get(id));
		}
		j.setMsg("删除利润分析成功");
		return j;
	}

	@ResponseBody
	@RequestMapping(value = "cx")
	public  String cx(String qyd,String dzs,String mdd,String min, String max,String pro){
		List<Profit> list;
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			list=cha(qyd,dzs,mdd,min,max,pro);
		}else{
			list=cha(qyd,dzs,mdd,min,max,UserUtils.getUseroffice());
		}

		Gson g=new Gson();
		return g.toJson(list).toString();
	}

public  List<Profit> cha(String qyd,String dzs,String mdd,String min, String max,String project){
	Profit p=new Profit();
	if(!project.equals("总部")){
		p.setPro(project);
	}
	p.setQyd(qyd);
	p.setDzd(mdd);
	p.setDzs(dzs);
	p.setMin(min);
	p.setMax(max);
	List<Profit> list=profitService.findList(p);
	Double zsr=0.0;
	Double zzc=0.0;
	Double zsj=0.0;
	String ids="";
	Double zzl=0.0;
	for(Profit pr:list){
		zsr+=Double.parseDouble(pr.getSr());
		zzc+=Double.parseDouble(pr.getZzc());
		zsj+=Double.parseDouble(pr.getSj());
		zzl+=Double.parseDouble(pr.getRemarks());
		ids+=pr.getId()+",";
	}
	Double mlr=zsr-zzc-zsj;
	Double lrl=(mlr)/zsr;
	Profit pro=new Profit();
	DecimalFormat df = new DecimalFormat("0.00%");
	NumberFormat nf = NumberFormat.getInstance();
	pro.setLr(nf.format(mlr));
	pro.setRemarks(ids);
	pro.setLrl(df.format(lrl));
	pro.setSr(nf.format(zsr));
	pro.setZzc(nf.format(zzc));
	pro.setSj(nf.format(zsj));
	pro.setDzs(nf.format(zzl));
	list.add(pro);
	return  list;
}
	/**
	 * 导出excel文件
	 */
	@ResponseBody
    @RequestMapping(value = "daochu")
	public void daochu0(HttpServletResponse response,String ids) {
		//获取数据
         String[] idd=ids.split(",");
         List<Profit> list =new ArrayList<Profit>();
         for(String id:idd){
         	list.add(profitService.get(id));
		 }

		Exportprofit e=new Exportprofit();
		e.exportprofit(response,list);
	}
	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:profit:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Profit> list = ei.getDataList(Profit.class);
			for (Profit profit : list){
				try{
					profitService.save(profit);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条利润分析记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条利润分析记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入利润分析失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/profit/?repage";
    }
	
	/**
	 * 下载导入利润分析数据模板
	 */
	@RequiresPermissions("fee:profit:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "利润分析数据导入模板.xlsx";
    		List<Profit> list = Lists.newArrayList(); 
    		new ExportExcel("利润分析数据", Profit.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/profit/?repage";
    }

}